package my_arrayList;/*
 *@ 代阳敲的专属代码
 **/

import java.lang.reflect.Array;
import java.util.Arrays;

public class T_arrayList<T extends Comparable> implements TList<T>{
    private T []element;
    private int capacity=1;
    private int usSize=0;

    public T_arrayList(Class<T> clazz) {
        element = (T[]) Array.newInstance(clazz, 1);
    }
    public T_arrayList() {
        element=(T[]) new Object[1];
    }

    @Override
    public void add(T data) {
        if(isFull()) {
            element=dilatation();
        }
        element[usSize]=data;
        usSize++;
    }
    private boolean isFull () {
        if(element.length==usSize) {
            return true;
        }
        return false;
    }
    private T[] dilatation () {
        return Arrays.copyOf(element,usSize*2);
    }

    @Override
    public void add(int pos, T data) {
        if(pos<0||pos>usSize) {
            throw new  PostException("post不合法");
        }
        if(isFull()) {
            element=dilatation();
        }
        int i=usSize-1;
        while(i>=pos) {
            element[i+1]=element[i];
            i--;
        }
        element[pos]=data;
        usSize++;

    }
    private  boolean isEmpty() {
        return element.length==0;
    }
    @Override
    public boolean contains(T toFind) {
        if(isEmpty()) {
            return false;
        }
        for (int i=0;i<usSize;i++) {
            if(toFind.compareTo(element[i])>0) {
                return true;
            }

        }
        return false;
    }

    @Override
    public int indexOf(T toFind) {
        if(isEmpty()) {
            return -1;
        }
        for (int i=0;i<usSize;i++) {
            if(element[i]==toFind) {
                return i;
            }

        }
        return -1;
    }

    @Override
    public T get(int pos) {
        if(pos<0||pos>usSize) {
            throw new  PostException("post不合法");
        }
        return element[pos];
    }

    @Override
    public void set(int pos, T value) {
        if(pos<0||pos>usSize) {
            throw new  PostException("post不合法");
        }
        element[pos]=value;
    }

    @Override
    public void remove(T toRemove) {
        int pos=indexOf(toRemove);
        if(pos==-1) {
            return;
        }
        while(pos<usSize-1) {
            element[pos]=element[pos+1];
            pos++;

        }
        usSize--;
    }

    @Override
    public int size() {
        return usSize;
    }

    @Override
    public void clear() {
        for (int i = 0; i <usSize ; i++) {
            element[i]=null;
        }
    }

    @Override
    public void display() {
        System.out.print("[");
        for (int i = 0; i < usSize ; i++) {
            System.out.print(element[i]);
            if(i<usSize-1) {
                System.out.print(",");
            }

        }
        System.out.print("]");
    }

}
